#######################################################################
# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# Openfuyao is licensed under Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
#######################################################################

import argparse
import logging
import os

from kubernetes import config, client
import yaml

config.load_kube_config()
apps_v1 = client.AppsV1Api()

logging.basicConfig(
    level=logging.INFO,
    format="%(levelname)s: %(message)s",
)


SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_YAML = os.path.join(SCRIPT_DIR, "temp-task.yaml")  # 模板文件路径


def validate_cpu(value):
    if not value.isdigit():
        raise ValueError(f"错误: CPU值 '{value}' 必须为整数")
    return int(value)


def generate_deployment(name, request, limit):
    with open(TEMPLATE_YAML, "r") as f:
        data = yaml.safe_load(f)

    data["metadata"]["name"] = name
    data["spec"]["selector"]["matchLabels"]["app"] = name
    data["spec"]["template"]["metadata"]["labels"]["app"] = name
    resources = data["spec"]["template"]["spec"]["containers"][0]["resources"]
    resources["requests"]["cpu"] = str(request)
    resources["limits"]["cpu"] = str(limit)

    return data


def deploy_temp_task(name, request, limit):
    request = validate_cpu(request)
    limit = validate_cpu(limit)
    try:
        body = generate_deployment(name, request, limit)
        apps_v1.create_namespaced_deployment(body["metadata"]["namespace"], body)
        logging.info(f"部署 {name} 成功")
    except Exception as e:
        raise RuntimeError(f"部署 {name} 失败: {e}") from e


def main():
    parser = argparse.ArgumentParser(add_help=False)
    parser.add_argument(
        "-n",
        "--name",
        required=True,
        help="部署名称（必填）",
    )
    parser.add_argument(
        "-r",
        "--request",
        required=True,
        help="CPU请求值（整数，必填）",
    )
    parser.add_argument(
        "-l",
        "--limit",
        required=True,
        help="CPU限制值（整数，必填）",
    )

    args = parser.parse_args()
    deploy_temp_task(args.name, args.request, args.limit)


if __name__ == "__main__":
    main()
